import com.sun.org.apache.xml.internal.resolver.helpers.PublicId;

/*
 *创建3个窗口卖票,使用多线程方式2Runnable方式
 * 线程安全已解决，使用同步方法
 *  */
public class RunnableDemo {
    public static void main(String[] args) {
        window w1 = new window();
        Thread t1 = new Thread(w1);
        Thread t2 = new Thread(w1);
        Thread t3 = new Thread(w1);
        t1.start();
        t2.start();
        t3.start();

    }
}

class window implements Runnable {
    private int ticket = 100;
    private Object obj = new Object();
    private synchronized void mmethod(){//使用同步方法的方式解决线程安全问题，方法中同步监视器为this
        if (ticket > 0) {
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName() + "第" + ticket + "张票");
            ticket--;
        }
    }
    @Override
    public void run() {
        while (true) {
           /* //同步代码块解决多线程安全问题
            //同步监视器，该程序中此方法监视器唯一
            //synchronized (obj) {
            synchronized (this){//此时的this唯一的window对象
                if (ticket > 0) {
                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println(Thread.currentThread().getName() + "第" + ticket + "张票");
                    ticket--;
                } else {
                    break;
                }*/
            mmethod();
        }
    }
}